<?php
/**
 * Created by xiaosong
 * E-mail:4155433@gmail.com
 * Date: 2019/10/8
 * Time: 11:45
 */


//修改报错级别

use App\Common\statement\ResponseStatement;
use App\Models\config\Config;
use App\Models\fund\Coupon;
use App\Models\goods\Order;
use Carbon\Carbon;
use \Illuminate\Support\Facades\DB;
function success($data = [],$status = ResponseStatement::HTTP_SUCCESS)
{

    if (is_numeric($status)){
        $message = ResponseStatement::$codeMessage[$status];
    }else{
        $message = $status;
        $status  = ResponseStatement::HTTP_SUCCESS;
    }

    return response([
        'code'    => $status,
        'message' => $message,
        'data'    => $data,
    ])->header('Content-Type', 'application/json');

}

function error($status = ResponseStatement::HTTP_ERROR,$data = [])
{

    if (is_numeric($status)){
        $message = ResponseStatement::$codeMessage[$status];
    }else{
        $message = $status;
        $status  = ResponseStatement::HTTP_ERROR;
    }

    return response([
        'code'    => $status,
        'message' => $message,
        'data'    => $data,
    ])->header('Content-Type', 'application/json');

}

/**
 * 生成项目uuid
 * Created by xiaosong
 * E-mail:4155433@gmail.com
 */
function getUuid()
{
    $fileName = base_path()."/uuid.json";
    $content = @file_get_contents($fileName);
    if (!$content){
        $content = ['id'=> DB::table('users')->orderBy('id','desc')->value('id')+1];
    }else{
        $content = json_decode($content,true);
    }
    $content['id'] ++;
    //以读写模式打开文件
    $file = fopen($fileName,"w");
    //将替换后的内容写入aa.txt文件中
    fwrite($file,json_encode($content));
    //关闭文件
    fclose($file);
    return $content['id'];
}

/**
 * api接口获取当前登录用户id
 */
function getUserId():int
{
    return auth('api')->id()??0;
}

/**
 * 获取已登录用户信息
 * Created by xiaosong
 * E-mail:4155433@gmail.com
 */
function getAuthUser()
{
    return  auth('api')->user();
}


/**
 * 加密id
 * @param int $str
 * @param int $length
 * @return string
 */
function hashid(int $str,int $length = 8) :string
{
    $hash = new \Hashids\Hashids(config('app.hash_key'), $length);
    return $hash->encode($str);
}


/**
 * 解密ID
 * @param string $str
 * @param int $length
 * @return int
 */
function dehashid(string $str,int $length = 8):int
{
    $hash = new \Hashids\Hashids(config('app.hash_key'), $length);
    $rs = $hash->decode($str);

    if (is_null($rs) || empty($rs)) {
        return 0;
    } else {
        return $rs[0];
    }
}

//判断是否为非0整数
function isInt( $num):bool
{

    if (!is_numeric($num)) return false;

    if ($num == 0) return false;

    if(floor($num)==$num){
        return true;
    }else{
        return false;
    }
}


function getMinUid($user_id){
    if (strlen($user_id) > 8){
        return hashid($user_id);
    }
    return $user_id;
}

/**
 * 隐藏手机号
 */
function hidePhone($phone)
{
    return substr_replace($phone,'****',3,-4);
}


function successWithMsg($message,$data = [],$status = ResponseStatement::HTTP_SUCCESS){

    if (is_numeric($message)){
        $message = ResponseStatement::$codeMessage[$message];
    }

    return response([
        'code'    => $status,
        'message' => $message,
        'data'    => $data,
    ])->header('Content-Type', 'application/json');
}
function getDistance($distance){
    if ($distance < 1){
        $distance = (int) $distance * 1000;
        if ($distance <= 0){
            $distance = 1;
        }
        $distance.='m';

    }else{
        $distance = round($distance,2).'km';
    }
    return $distance;
}

/**
 * curl get 请求
 * @param string $url
 * @param array $headers
 * @return mixed
 */
function curl_get(string $url,array $headers = [])
{
    header('content-type:text/html;charset=utf-8');
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    if (1 == strpos("$".$url, "https://"))
    {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $data = curl_exec($curl);
    curl_close($curl);


    $result = json_decode($data, true);

    return $result;
}

/**
 * PHP计算两个时间段是否有交集（边界重叠不算）
 *
 * @param string $beginTime1 开始时间1
 * @param string $endTime1 结束时间1
 * @param string $beginTime2 开始时间2
 * @param string $endTime2 结束时间2
 * @return bool
 */
function is_time_cross( $beginTime1 = '', $endTime1 = '', $beginTime2 = '', $endTime2 = ''):bool
{
    $status = $beginTime2 - $beginTime1;
    if ($status > 0){
        $status2 = $beginTime2 - $endTime1;
        if ($status2 > 0){
            return false;
        }elseif ($status2 < 0){
            return true;
        }else{
            return false;
        }
    }elseif($status < 0){
        $status2 = $endTime2 - $beginTime1;
        if ($status2 > 0){
            return true;
        }else if ($status2 < 0){
            return false;
        }else{
            return false;
        }
    }else{
        $status2 = $endTime2 - $beginTime1;
        if ($status2 == 0){
            return false;
        }else{
            return true;
        }
    }
}


/**
 * 数组位置交换
 * @param $arr
 * @param $arg1
 * @param $arg2
 * @return mixed
 */
function array_exchange($arr, $arg1, $arg2)
{
    $r = range(0, count($arr) - 1);
    $res = $res_bak = array_combine($r, array_keys($arr));
    $change = array($arg1, $arg2);
    list($res[array_search($change[0], $res_bak)], $res[array_search($change[1], $res_bak)]) = array($change[1], $change[0]);
    foreach ($res as $v) {
        $array[$v] = $arr[$v];
    }
    return $array;
}

/**
 * 获取单价
 * @param \App\Models\goods\ShopCar $car
 * @return float|void
 */
function getPrice(\App\Models\goods\ShopCar $car,\App\Models\User $user,$getField = false){
    //判断用户显示的价格
    if ($car->goods->is_sr && isBirthday($user)){
        $p = 'sr_price';
    }elseif ($car->goods->is_xql && isSaturday()){
        $p = 'xql_price';
    } elseif ($user->level == 2 && $car->num >= $car->goods->detail->shop_num){//小店用户
        $p = 'shop_price';
    }elseif ($user->level == 3 && $car->num >= $car->goods->detail->business_num){//企业用户
        $p = 'business_price';
    }else{
        $p = 'price';
    }
    if ($car->spec){
        $price =  $car->spec->{$p};
    }else{
        if ($p != 'price'){
            $price = $car->goods->detail->{$p};
        }else{
            $price = $car->goods->{$p};
        }
    }
    if ($getField){
        return [$price,$p];
    }
    return $price;

}

/**
 * 判断当天是否为用户生日
 * @param null $date
 * @return bool
 */
function isBirthday(\App\Models\User $user) :bool
{
    if ($user->birthday == date('Y-m-d')){
        return true;
    }else{
        return false;
    }
}

/**
 * 判断当天是否为星期六
 * @return bool
 */
function isSaturday():bool
{
    return Carbon::now()->dayOfWeek == 6;
}

function getExpresses(){

    $rows = \Illuminate\Support\Facades\Cache::get("getExpressesCache");

    if ($rows){
        return $rows;
    }

    try{
        $rows = Jormin\KDNiao\KDNiao::expresses();
    }catch (Exception $e){

    }

    if (is_array($rows) && count($rows) > 1){
        $rows = array_pluck($rows,'name','code');
        \Illuminate\Support\Facades\Cache::put("getExpressesCache",$rows,60);
        return $rows;
    }
    return [];
}

/**
 * @param $user_id  下单用户
 * @param $to_user  上级用户
 */
function firstGive($user_id,$to_user){
    $where['user_id'] = $user_id;
    $where[] = ['status','!=',0];
    $count = Order::where($where)->count();
    if ($count == 1){//赠送优惠券
        $item1['amount'] = Config::getConfig('first_money')??1;
        $item1['title'] = Config::getConfig('first_title')??"邀请好友首次下单赠送";
        $item1['quota'] = Config::getConfig('first_quota')??0;
        $item1['end_at'] = Carbon::now()->addDays(Config::getConfig('first_days')??60);
        $item1['user_id'] = $to_user;
        $item1['status'] = 1;
        $items1[] = $item1;
        $items1[] = $item1;
        Coupon::insert($items1);
        return true;
    }
    return false;
}


/**
 * @param int $user_id 用户ID
 * @param float $amount 金额
 * @param string $title 标题
 * @param int $pm 获取类型 0 = 支出 1 = 获得
 */
function moneyDetailAdd(int $user_id, float $amount, string $title, int $pm = 1)
{
    if ($amount == 0){
        return false;
    }

    \App\Models\user\MoneyDetail::create([
        'user_id' => $user_id,
        'amount' => $amount,
        'title' => $title,
        'pm' => $pm,
    ]);

}



/**
 * 求两个已知经纬度之间的距离,单位为米
 */
function getDistance2($lng1, $lat1, $lng2, $lat2) {
    if (empty($lng1) || empty($lat1)){
        return "";
    }
    if (empty($lng2) || empty($lat2)){
        return "";
    }

    // 将角度转为狐度
    $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;

    if ($s > 300000){
        return "";
    }

    return bcdiv($s,1000,2)."km";

}

/**
 * 获取用户关注的育婴师数量
 * @return mixed
 */
function getFollowMajorsSum($id,$user_ids)
{
    if (empty($user_ids)){
        return 0;
    }
    $map['major_id'] = $id;
    return \App\Models\nursery\UserMajor::where($map)->whereIn('user_id',$user_ids)->count();
}